package com.xtaller.sdboot.utils.helper;

import lombok.var;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : Taller
 * @date : 2020/2/7 08:11
 * @Description : 模拟全局缓存类
 */
public class LocalHelper {
    public static Map<String, CacheData> CACHE_DATA = new ConcurrentHashMap<String, CacheData>();

    public static Object get(String key, Load load, int expire){
        var data = get(key);
        if(data == null && load != null){
            data = load.load();
            if(data != null){
                set(key,data,expire);
            }
        }
        return data;
    }
    public static Object get(String key){
        CacheData data = CACHE_DATA.get(key);
        if(data != null ){
            if(data.getExpire() <= 0 || data.getSaveTime() >= TimeHelper.getTimestamps()) {
                return data.getData();
            }
        }
        return null;
    }

    public static void set(String key, Object data, int expire){
        var value = "";
        if(data.getClass().isPrimitive()) {
            value = data.toString();
        }else {
            value = JsonHelper.o2s(data);
        }
        CACHE_DATA.put(key,new CacheData(value, expire));
    }
    public static void clear(String key){
        CACHE_DATA.remove(key);
    }
    public static void clearAll(){
        CACHE_DATA.clear();
    }
    public interface Load {
        Object load();
    }
    private static class CacheData {
        CacheData(Object t,int expire){
            this.data = t;
            this.expire = expire <= 0 ? 0 : expire * 1000;
            this.saveTime = TimeHelper.getTimestamps() + this.expire;
        }
        private Object data;

        /**
         * 存活时间
         * */
        private long saveTime;
        /**
         * 过期时间 小于等于0标识永久存活
         * */
        private long expire;

        public Object getData() {
            return data;
        }
        public long getExpire() {
            return expire;
        }
        public long getSaveTime() {
            return saveTime;
        }
    }
}
